export class TTSOptions {
    public AppKey: string = '';
    public Text: string = '';
    public Token: string = '';
    /**
     * 音频编码格式，支持pcm/wav/mp3格式。默认值：pcm。
     */
    public Format: 'pcm' | 'wav' | 'mp3' = 'pcm';
    /**
     * 音频采样率，支持16000 Hz和8000 Hz，默认值：16000 Hz。
     */
    public SampleRate: 16000 | 8000 = 16000;
    /**
     * 发音人，默认值：xiaoyun。更多发音人请参见接口说明(https://help.aliyun.com/document_detail/84435.htm?spm=a2c4g.11186623.0.0.2d8a2807ABFWvZ#topic-2572243)。
     */
    public Voice: string = 'xiaoyun';
    /**
     * 音量，取值范围：0~100，默认值：50。
     */
    public Volume: number = 50;
    /**
     * 语速，取值范围：-500~500，默认值：0。
     */
    public SpeechRate: number = 0;
    /**
     * 语调，取值范围：-500~500，默认值：0。
     */
    public PitchRate: number = 0;

    public static WithTextFormat(text: string, format: 'pcm' | 'wav' | 'mp3' = 'wav'): TTSOptions {
        const options = new TTSOptions();
        options.Text = text;
        options.Format = format;
        return options;
    }
}

/**
 * TTS组件
 */
export default class TTSComponent {
    private static instance: TTSComponent = new TTSComponent();
    /**
     * TTS组件
     */
    public static get Default(): TTSComponent {
        return this.instance;
    }

    constructor() {
        window.addEventListener('unload', this.Dispose.bind(this));
    }

    Dispose() {
        window.removeEventListener('unload', this.Dispose);
    }

    private appKey: string = 'Lk8UVU6n8HlnpkJt';
    private tokenUrl: string = 'http://virtual.eduhenghong.cn:4499/api/AlyServer/GetAccessToken';
    private token: string = '';

    public async ParseAsync(input: string | TTSOptions): Promise<string> {
        if (this.token == '') {
            const response = await window.fetch(this.tokenUrl, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                },
            });

            const result: { success: boolean, result: string, msg: string } = await response.json();
            if (result.success) {
                this.token = result.result;
            } else {
                window.Logger.Error(`获取阿里云TTS令牌失败,${result.msg}`);
            }
        }

        let url = 'https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts?';
        if (typeof input == 'string') {
            const options = TTSOptions.WithTextFormat(input);
            options.AppKey = this.appKey;
            options.Token = this.token;

            url += this.CalculateUrlParamters(options);
        } else {
            input.AppKey = input.AppKey == '' ? this.appKey : input.AppKey;
            input.Token = input.Token == '' ? this.token : input.Token;

            url += this.CalculateUrlParamters(input);
        }

        return url;
    }

    private CalculateUrlParamters(options: TTSOptions): string {
        let parameters: Array<string> = [];
        parameters.add(`appkey=${options.AppKey}`);
        parameters.add(`text=${window.encodeURI(options.Text)}`);
        parameters.add(`token=${options.Token}`);

        if (options.Format != 'pcm') {
            parameters.add(`format=${options.Format}`);
        }

        if (options.SampleRate != 16000) {
            parameters.add(`sample_rate=${options.SampleRate}`);
        }

        if (options.Voice != 'xiaoyun') {
            parameters.add(`voice=${options.Voice}`);
        }

        if (options.Volume != 50) {
            parameters.add(`volume=${options.Volume}`);
        }

        if (options.SpeechRate != 0) {
            parameters.add(`speech_rate=${options.SpeechRate}`);
        }

        if (options.PitchRate != 0) {
            parameters.add(`pitch_rate=${options.PitchRate}`);
        }

        return parameters.join('&');
    }
}